package com.atguigu.gmall.oauth.service.impl;

import com.atguigu.gmall.oauth.service.LoginService;
import com.atguigu.gmall.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * 登录接口实现类
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    RestTemplate restTemplate;
    /**
     * 登录方法
     *  @param username
     * @param password
     * @return
     */
    @Override
    public AuthToken login(String username, String password) {
        //参数校验
        if (StringUtils.isEmpty(username) ||
            StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码不能为空");
        }
        //获取url
        String url = "http://localhost:9001/oauth/token";
        //设置 5个参数
        //初始化请求头
        MultiValueMap headers = new HttpHeaders();
        headers.set("Authorization", getAuthorization());
        //初始化请球体
        MultiValueMap body = new HttpHeaders();
        body.set("username",username);
        body.set("password",password);
        body.set("grant_type","password");
        //初始化返回参数
        HttpEntity httpEntity = new HttpEntity(body,headers);
        //生成令牌
        ResponseEntity<Map> exchange =
                restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        //获取返回结果
        Map<String,String> result = exchange.getBody();
        //获取令牌
        String accessToken = result.get("access_token");
        //获取刷新令牌
        String refreshToken = result.get("refresh_token");
        //去获取令牌Id jti
        String jti = result.get("jti");
        //返回对象初始化
        AuthToken authToken = new AuthToken();
        authToken.setRefreshToken(refreshToken);
        authToken.setJti(jti);
        authToken.setAccessToken(accessToken);
        //根据5个参数生成令牌 并返回
        return authToken;

    }
    @Value("${auth.clientId}")
    public String clientId;
    @Value("${auth.clientSecret}")
    public String clientSecret;

    private String getAuthorization() {
        String a = clientId + ":"+clientSecret;
        byte[] encode = Base64.getEncoder().encode(a.getBytes());
        return "Basic "+new String(encode);
    }
}
